/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Cart;
import model.DBFunction;
import model.Product;
import model.ReturnedProducts;

/**
 *
 * @author ThanhTrung
 */
public class ProductServlet extends HttpServlet {

    public static final String CART_NAME = "cart";

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("action : parameter :" + request.getParameter("action"));
        HttpSession session = request.getSession();
        if (session.getAttribute(CART_NAME) == null) {
            Cart cart = new Cart();
            session.setAttribute(CART_NAME, cart.getCart());
        }
        int categoryId = 0;
        int pageIndex = 0;
        final int numRows = 8;

        if (request.getParameter("page") == null) {
            pageIndex = 0;
        } else {
            pageIndex = Integer.parseInt(request.getParameter("page").toString());
        }
        if (request.getParameter("categoryId") == null || request.getParameter("categoryId").equals("")) {
            categoryId = 1;
        } else {
            categoryId = Integer.parseInt(request.getParameter("categoryId").toString());
        }

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        System.out.println("action :" + request.getParameter("action"));
        try {
            String method = request.getParameter("action");
            if ("purchase".equalsIgnoreCase(method)) {
                purchase(request, response);
            } else {

                DBFunction db = new DBFunction();
                ReturnedProducts rp = db.getProducts(categoryId, pageIndex, numRows);
                ArrayList<Product> pros = rp.getProducts();
                String categoryName = rp.getCategoryName();
                int categoryProductCount = rp.getCategoryProductCount();

                out.println("<div class=\"center_title_bar\">" + categoryName + "</div>");
                if (pros.size() == 0) {
                    out.println("<br/><br/><br/><br/><br/><div align=\"center\">Không có sản phẩm nào thuộc danh mục này.</div><br/><br/><br/><br/><br/>");
                }
                for (int i = 0; i < pros.size(); i++) {
                    out.println("<div class=\"prod_box\">");
                    out.println("<div class=\"top_prod_box\"></div>");
                    out.println("<div class=\"center_prod_box\">");
                    out.println("<div class=\"product_title\"><a href=\"details.jsp?productId=" + pros.get(i).getProductId() + "\">" + pros.get(i).getProductName() + "</a></div>");
                    out.println("<div class=\"product_img\"><a href=\"details.jsp?productId=" + pros.get(i).getProductId() + "\"><img src=\"" + pros.get(i).getPicture() + "\" alt=\"\" border=\"0\" width=\"115px\" height=\"86px\" /></a></div>");
                    out.println("<div class=\"prod_price\"><span class=\"reduce\">350$</span> <span class=\"price\">" + pros.get(i).getUnitPrice() + "$</span></div>");
                    out.println("</div>");
                    out.println("<div class=\"bottom_prod_box\"></div>");
                    out.println("<div class=\"prod_details_tab\">");
                    out.println(" <a href=\"\" title=\"header=[Add to cart] body=[&nbsp;] fade=[on]\" onclick=\"addToCart(" + pros.get(i).getProductId() + ")\">");
                    //out.println(" <a  title=\"header=[Add to cart] body=[&nbsp;] fade=[on]\" onclick=\"addToCard(" + pros.get(i).getProductId() + ")\">");
                    out.println("<img src=\"images/cart.gif\" alt=\"\" border=\"0\" class=\"left_bt\" />");
                    out.println("</a> <a href=\"#\" title=\"header=[Specials] body=[&nbsp;] fade=[on]\">");
                    out.println("<img src=\"images/favs.gif\" alt=\"\" border=\"0\" class=\"left_bt\" />");
                    out.println("</a> <a href=\"#\" title=\"header=[Gifts] body=[&nbsp;] fade=[on]\">");
                    out.println("<img src=\"images/favorites.gif\" alt=\"\" border=\"0\" class=\"left_bt\" /></a>");
                    out.println(" <a href=\"details.jsp?productId=" + pros.get(i).getProductId() + "\" class=\"prod_details\">details</a> </div>");
                    out.println("</div>");

                }
                String next = "";
                String previous = "";
                String current;

                current = (pageIndex + 1) + " / " + (categoryProductCount / numRows + 1);
                out.println("<div class=\"center_title_bar\" style=\"text-align:center;\">");
                if (pageIndex > 0) {
                    out.println("<a href=\"#\"  style=\"text-decoration:none;color:gray;margin-left:0px;float:left;margin-left: 15px;\" onclick=\"getProducts(" + categoryId + "," + (pageIndex - 1) + ")\">Previous</a>");
                }
                out.println("<a href=\"#\" style=\"text-align:center;text-decoration:none;color:gray;\" >" + current + "</a>");
                if (pageIndex < (categoryProductCount / numRows)) {
                    out.println("<a href=\"#\"  style=\"text-decoration:none;color:gray;margin-left:0px;float:right;margin-right: 15px;\" onclick=\"getProducts(" + categoryId + "," + (pageIndex + 1) + ")\">Next</a>");
                }
                out.println("</div>");
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    private void purchase(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int quantity =0;
        double total =0;
        Cart cart = new Cart();
        
        Hashtable<Integer, Integer> cht = (Hashtable<Integer, Integer>) request.getSession().getAttribute(CART_NAME);
        if (cht != null) {
            cart.setCart(cht);
        }
        int productId = Integer.valueOf(request.getParameter("productId").toString());
        cart.purchase(productId);
        request.setAttribute(CART_NAME, cart.getCart());
      
       

        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();

        total = cart.getTotal(cart.getCart());
        quantity = cart.getQuantity(cart.getCart());

        out.println("<div class=\"shopping_cart\">");
        out.println("<div class=\"cart_title\">Shopping cart</div>");
        out.println("<div class=\"cart_details\"> " + quantity + " items <br />");
        out.println("<span class=\"border_cart\"></span> Total: <span class=\"price\">" + total + "$</span> </div>");
        out.println("<div class=\"cart_icon\"><a href=\"checkout.jsp\" title=\"header=[Checkout] body=[&nbsp;] fade=[on]\"><img src=\"images/shoppingcart.png\" alt=\"\" width=\"48\" height=\"48\" border=\"0\" /></a></div>");
        out.println("</div>");
        out.println("<div class=\"title_box\">What’s new</div>");
        out.println("<div class=\"border_box\">");
        out.println("<div class=\"product_title\"><a href=\"details.html\">Motorola 156 MX-VL</a></div>");
        out.println("<div class=\"product_img\"><a href=\"details.html\"><img src=\"images/p2.gif\" alt=\"\" border=\"0\" /></a></div>");
        out.println("<div class=\"prod_price\"><span class=\"reduce\">350$</span> <span class=\"price\">270$</span></div>");
        out.println("</div>");
        System.out.println("total : " + total);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
